package com.common.image_loader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.baidu.common.utils.Base64;
import com.baidu.common.utils.FileUtil;
import com.baidu.common.utils.Security;
import com.japher.hackson.utils.Tools;

public class LocalImageManager
{

	final public static int SUCCESS = 0;
	final public static int ERR_SD_INVALID = -1;
	final public static int ERR_NO_SPACE = -2;
	final public static int ERR_FILE_EXISTS = -3;
	final public static int ERR_CREATE_FILE = -4;
	final public static int ERR_IO = -5;
	
	final public static long MAX_CACHE_INTERVAL = 10 * 25 * 3600 * 1000;
	
	public static String dbPath = Environment.getExternalStorageDirectory() + File.separator + "NTESMovie" + File.separator;
	static String path = dbPath;

	static
	{
		File file = new File(path);
		if (!file.exists())
		{
			file.mkdirs();
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{

			}
		}
	}

	public static void setPath(String path)
	{
		LocalImageManager.path = path;

	}

	/*
	 * public static String getSmallUrlImage(String url) { int
	 * index=url.lastIndexOf("."); String small=url.substring(0, index);
	 * small+="_small"; small+=url.substring(index); return small; }
	 */
	public static void clean()
	{
		File file = new File(path);
		if (!file.exists() || !file.isDirectory())
			return;

		File files[] = file.listFiles();
		if (files != null)
		{
			for (int i = 0; i < files.length; i++)
				files[i].delete();
		}
	}

	public static String getCacheSize()
	{
		try
		{
			return FileUtil.getAutoFileOrFilesSize(dbPath);
		}
		catch (Exception e)
		{
			return "";
		}
		
	}
	
	public static int saveBmp(Bitmap bmp, String name)
	{
		if (bmp == null)
			return ERR_IO;
		try
		{

			File file = new File(path + name);
			if (file.exists())
				return ERR_FILE_EXISTS;
			if (file.createNewFile())
			{
				FileOutputStream out = new FileOutputStream(file);
				bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
				out.flush();
				out.close();
			}
			else
				return ERR_CREATE_FILE;

			return SUCCESS;

		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("finish write:" + name);
			return ERR_IO;

		}
	}

	public static int saveString(String data,String fileName,boolean isSecure)
	{
		if (Tools.isEmpty(data))
			return ERR_IO;
		try
		{

			File file = new File(path + fileName);
			if (file.exists())
			{
				file.delete();
			}
			
			if (file.createNewFile())
			{
				FileOutputStream out = new FileOutputStream(file);
				
				byte [] buffer = null;
				if(isSecure)
				{
					byte [] b = Security.encrypt(data.getBytes());
					String target = Base64.encode(b);
					buffer = target.getBytes();
				}
				out.write(buffer);
				out.flush();
				out.close();
			}
			else
				return ERR_CREATE_FILE;

			return SUCCESS;

		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("finish write:" + fileName);
			return ERR_IO;

		}
	}
	
	public static String readLocalStr(String fileName)
	{
		String result = "";
		File file = new File(path + fileName);
		if (file.exists())
		{
			FileInputStream input = null;
			try
			{
				input = new FileInputStream(file);
				ByteArrayOutputStream reader = new ByteArrayOutputStream();
				
				byte [] data = new byte[1024];
				if(input.read(data) != -1)
				{
					reader.write(data);
				}
				data = null;
				result = new String(reader.toByteArray());
				
				if(!Tools.isEmpty(result))
				{
					data = Base64.decode(result);
					data = Security.decrypt(data);
					result = new String(data);
				}
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			finally{
				try
				{
					if(input != null)
					{
						input.close();
					}
				}
				catch(Exception e)
				{
					
				}
			}
		}
		return result;
	}
	
	public static int saveImage(String name, InputStream in)
	{

		// if(DeviceInfo.hasSdCard())
		{
			try
			{
				// if(DeviceInfo.freeSpaceOnSd()<in.available())
				{
					// return ERR_NO_SPACE;
				}
				long t1 = System.currentTimeMillis();
				long l = 0;
				// System.out.println("write:"+name);
				File file = new File(path + name);
				if (file.exists())
					return ERR_FILE_EXISTS;
				if (file.createNewFile())
				{
					FileOutputStream out = new FileOutputStream(file);

					byte data[] = new byte[512];
					while (true)
					{
						try
						{
							int len = in.read(data);
							out.write(data, 0, len);
							l += len;
						}
						catch (Exception e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
							break;
						}
					}
					out.flush();
					out.close();

				}
				else
					return ERR_CREATE_FILE;

				return SUCCESS;

			}
			catch (IOException e)
			{
				e.printStackTrace();
				return ERR_IO;
			}
			finally
			{
				try
				{
					in.close();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		// else
		// return ERR_SD_INVALID;

	}

	public static int saveImage(String name, byte[] data)
	{

		try
		{
			File file = new File(path + name);
			if (file.exists())
				return ERR_FILE_EXISTS;
			if (file.createNewFile())
			{
				FileOutputStream out = new FileOutputStream(file);

				out.write(data);

				out.close();
			}
			else
				return ERR_CREATE_FILE;

			return SUCCESS;

		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("finish write:" + name);

		}
		return ERR_IO;

	}

	public static Bitmap loadImage(String name)
	{
		final String filePath = path + name;
		Bitmap b = null;
		try
		{
			b = BitmapFactory.decodeFile(filePath);
			if(b != null)
			{
				updateFileTime(filePath);
			}
			else
			{
				delImage(name);
			}
		}
		catch (Exception e)
		{
			// 有可能是图片数据保存不完整导致失败，所以这里删除旧数据
			delImage(name);
		}
		catch (OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
		}

		return b;
	}

	public static long getFileSize(String name)
	{
		File file = new File(path + name);
		if (!file.exists())
			return -1;
		else
			return file.length();
	}

	public static boolean delImage(String name)
	{
		boolean r = false;
		try
		{
			File file = new File(path + name);
			if (file.exists())
				r = file.delete();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return r;
	}

	public static void updateFileTime(String path)
	{
		try
		{
			File file = new File(path);
			long newModifiedTime = System.currentTimeMillis();
			file.setLastModified(newModifiedTime);
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}
	}
	
	public static void deleteExpiredCache()
	{
		new Thread(new Runnable()
		{
			
			@Override
			public void run()
			{
				File [] files = new File(dbPath).listFiles();
		    	
		    	if(files!=null)
		    	{
		    		//Arrays.sort(files, new FileLastModifSort());
		    		
		    		for(int i =0; i < files.length ; i++)
			    	{
			    		final File file = files[i];
			    		long now = System.currentTimeMillis();
			    		if(now - file.lastModified() > MAX_CACHE_INTERVAL)
			    		{
			    			file.delete();
			    		}
			    	}
		    	}
			}
		}).start();
		
	}
	
	/** 
	 * sort local picture files by their last modified time 
	 */ 
	@SuppressWarnings("unused")
	private static class FileLastModifSort implements Comparator<File>
	{ 
	    public int compare(File arg0, File arg1) 
	    { 
	        if (arg0.lastModified() >arg1.lastModified()) 
	        { 
	            return 1; 
	        } 
	        else if (arg0.lastModified() ==arg1.lastModified()) 
	        { 
	            return 0; 
	        } 
	        else 
	        { 
	            return -1; 
	        } 
	    } 
	} 
}
